#!/usr/bin/env node
// 为markdown多级标题生成目录
const os = require('os');
const fs = require('fs');
const path = require('path');
const moment = require('moment');

let args = new Map();
process.argv.splice(2).forEach(arg => {
  const [ key, value ] = arg.split('=')
  args.set(key, value)
})
const file = args.get('file')
if(!file) {
  console.error(`[ReferenceError]: must have file param`);
  process.exit()
}
const [ fileName, ext ] = file.split('.')
const out = args.get('out') || `${fileName}-menu.${ext}`

try {
    const data = fs.readFileSync(path.resolve(process.cwd(), file), 'UTF-8');
    const lines = data.split(/\r?\n/);
    const menu = [];
    let reFile = '';
    
    lines.forEach((line, index) => {
      const lineTitle = line.match(/^#+(?=\s)/g)
      const lineContent = line.match(/(?<=#+\s).+/g);
      if(lineTitle) {
        const ran = moment().format('x') + index
        reFile += `${lineTitle} <span id=${ran}>${lineContent}</span>${os.EOL}`
        menu.push(`[${lineContent}](#${ran})${os.EOL}${os.EOL}`)
      }else {
        reFile += `${line}${os.EOL}`
      }
    });

    reFile = menu.join('') + reFile;

    fs.writeFileSync(path.resolve(process.cwd(), out), reFile);
    console.log('generate successfully')
} catch (err) {
    console.error(err);
}
process.exit()